const db = require("../db/mysql");
const { UUID } = require("../utils/config");
const getTime = require("../utils/getTime");

const logins={
    /**
     * 根据oppenid为查询是否已经登录过
     * @param {*} openid 
     */
    getUserByOpenID:async(openid)=>{
        const sql = "select *from users where uopenid=?";  
        const result = await db.query(sql, openid);
        if (result == null || result.length == 0) {
            return null;
          } else {
            return result[0];
          }
    },
    /**
     *  点击绑定用户时触发,验证账号与验证码
     */
    smsLoginverify:async(phone,verifySms,openid)=>{
        const sql = "SELECT * from verify WHERE VPhone=? and  VCode=? ORDER BY VCreateTime desc LIMIT 1";
        const result= await db.query(sql,phone,verifySms);

        let nowVerify= result[0];
        //验证码错误或者是不是本次登录的验证码
        if(result==null  || result.length == 0 || nowVerify.VIsUse == 1 ){
            return {
                code:"-1",
                message:"验证码错误,请输入正确的验证码"
            }
        }

        const outTime = new Date(nowVerify.VOutTime);
        const now = new Date();
        //看最新的验证码是否已经失效
        if(now>outTime){
            return {
                code: -1,
                message: "验证码已失效,请重新获取",
              };
        }

        const sql4 = "SELECT * from verify WHERE VPhone=?  ORDER BY VCreateTime desc LIMIT 1";
        const result4= await db.query(sql4,phone,verifySms);
        //输入的验证码不是最新获取到的
        if(result4[0].VIsUse==0 && verifySms!=result4[0].VCode){
                return {
                    code: -1,
                    message: "请输入最新的验证码",
                  };
        }

       //正确的验证码
    const sql2 = `update users set UOpenID=? where uaccount=?`;
    const yesResult = await db.query(sql2, openid, phone);
    if (yesResult == null) {
      return {
        code: -500,
        message: "绑定失败",
      };
    }

        //将所有该手机号的所有验证码设定为已使用
        const sql3 = `update verify set VIsUse=1 where VPhone=?`;
        await db.query(sql3,nowVerify.VPhone);
        return {
          code: 0,
          message: "ok",
        };
      },
    /**
     * 验证是否为受邀请用户 是的话下发验证码
     * @param {*} phone 
     * @returns 
     */
    verifyIsInvitedUser:async(phone)=>{
        const sql = "select *from users where uaccount=?";
        const result= await db.query(sql,phone);
        if(result==null  || result.length == 0){
            return null
        }
         return result[0]
       
    },

    /**
     * 确认为受邀用户,在数据库中添加验证码
     * @param {*} phone 
     * @param {*} verifySms 
     * @returns 
     */
    addPhoneVerifySms:async(phone,verifySms)=>{
        const sql = `insert into verify values
        (
          ?,?,?,?,?,0,null,null
        )`;
       const nowTimestamp=Date.parse(new Date());
       const lapseTimestamp=Date.parse(new Date())+300000;
       const nowTime= getTime.getTime(nowTimestamp);
       const lapseTime=getTime.getTime(lapseTimestamp);
       const result=await db.query(sql,UUID(),phone,verifySms,nowTime,lapseTime);
       if(result.affectedRows>0){
            return true
       }else{
            return true
       }
    },
    /**
     * 获取当前登录用户信息
     * @param {*} token 
     * @returns 
     */
    getCurrUser:async (token)=>{
        const sql="select * from users where UToken=? ";
        const result=await db.query(sql,token.tokens);
        return result[0]
    },

    /**
     * 用户登录
     * @param {*} account 账号
     * @param {*} password 密码
     * @returns 
     */
    login: async (account,password)=>{
        const sql="select * from users where Uaccount=? and Upassword=? ";
        const result=await db.query(sql,account,password);
        if(result==null){
            return{
                code:-500,
                message:"无法登录,请联系管理员进行处理!!!"
            }
        }

        if(result.length==0){
            return{
                code:-1,
                message:"账号密码有误,请重新登录"
            }
        }else{
            return{
                code:0,
                message:"ok"
            }
        }
    },
    /**
     * 设置token初始令牌
     * @param {} code 
     * @param {*} account 
     * @returns 
     */
    setToken:async (code,account)=>{
        const sql="update users set UToken=? where Uaccount=?";
        let result=await db.query(sql,code,account);
        return result
    }
}

module.exports=logins;